import React, { memo, useEffect, useState } from "react";
import type { FC, ReactNode } from "react";
import { QueryPageWrapper } from "./style";
import { useAppDispatch, useAppSelector } from "@/store";
import { shallowEqual } from "react-redux";
import { QRCode } from "antd";
import { feachAccountQrAction, feachExamineQrAction, feachLoginQrAction } from "@/store/modules/login";
import { useNavigate } from "react-router-dom";

interface IProps {
  children?: ReactNode;
}

const QueryPage: FC<IProps> = () => {
  // 控制二维码的状态
  const [status, setStatus] = useState<"active" | "loading" | "expired" | undefined>('active')
  // 是否是第一次进入
  const [isShowQr, setIsShowQr] = useState(true)
  // 是否请求新的二维码
  const [isQuery, setIsQuery] = useState(true)
  let trime: any = null

  const { qrCode } = useAppSelector((state) => ({
    qrCode: state.login.qrCode,
  }), shallowEqual)

  useEffect(() => {
    handleQrData()
    console.log(33)
    // 组件卸载时 我们就清除我们的延时器
    return () => {
      clearInterval(trime)
    }
  }, [qrCode])

  const dispatch = useAppDispatch()
  const navigate = useNavigate()

  const handleQrData = () => {
    // 获取我们的新的qr二维码
    if (isQuery) {
      dispatch(feachAccountQrAction())
      setIsQuery(false)
    }

    trime = setInterval(async () => {
      if (isShowQr === false) {
        clearInterval(trime)
      } else {
        // 检查qr是否失效
        await dispatch(feachExamineQrAction(null))
        // 400 为二维码过期, 801 为等待扫码, 802 为待确认, 803 为授权登录成功
        if (qrCode === 400) {
          // 清除
          clearInterval(trime);
          setIsQuery(true)
          setIsShowQr(false)
          setStatus("expired")
        } else if (qrCode === 802) {
          console.log(333)
          setStatus("loading")
        } else if (qrCode === 803) {
          await dispatch(feachLoginQrAction("queryType"))
          setIsShowQr(false)
          // 清除延时器
          clearInterval(trime)
          navigate("/musiclibrary")
        }
      }
    }, 1000)
  }

  const { qrUrl } = useAppSelector((state) => ({
    qrUrl: state.login.qrUrl
  }), shallowEqual)

  // 重新加载二维码
  const handleRefresh = () => {
    handleQrData()
    setIsShowQr(true)
  }

  return <QueryPageWrapper>
    {qrUrl && <QRCode
      value={qrUrl}
      color="#335eea"
      bgColor="#bbcdff"
      status={status}
      icon={require("@/assets/img/coderFy.png")}
      size={230}
      onRefresh={handleRefresh}
    />}
    <div className="account-message">
      打开网易云音乐APP扫码登录
    </div>
  </QueryPageWrapper>;
};

export default memo(QueryPage);